//
//  SitesListViewController.m
//  rss_reader
//
//  Created by Oleg Soldatoff on 4/13/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SitesListViewController.h"

@implementation SitesListViewController
@synthesize sites = _sites;
@synthesize discoverFeedsViewController = _discoverFeedsViewController;
@synthesize base = _base;

@synthesize sitesArray = _sitesArray;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
       // Custom initialization
      self.base = [[[DataBase alloc]init]autorelease];
     
    }
    return self;
}

- (void) dealloc {
  
  [_sites release];
  [_discoverFeedsViewController release];
  [_base release];
  [super dealloc];
}


-(void) viewWillAppear:(BOOL)animated {
  
//  if (self.discoverFeedsViewController != nil) {
//    //self.sites =  [[DataBase sharedDatabase]  dicWithSitesAndFeeds];   
//    self.discoverFeedsViewController = nil;
//    [self.tableView reloadData];
//  }
//  [self.tableView reloadData];  
  self.sitesArray = nil;
  [self.tableView reloadData];  
  [[NSNotificationCenter defaultCenter] addObserver:self 
                                           selector:@selector(pocessNotification:)  
                                               name:@"BaseUpdated" 
                                             object:nil];
  
  
  
//  [DataBase sharedDatabase].siteID = nil;
//  [DataBase sharedDatabase].baseFeedsForSiteID = nil;
//  [DataBase sharedDatabase].baseArticles = nil;
//  [[DataBase sharedDatabase].feedURL removeAllObjects];
//  for (NSDictionary *dic in [DataBase sharedDatabase].baseFeedsForSiteID) {
//    [[DataBase sharedDatabase].feedURL addObject:[dic valueForKey: @"URL"]];
//  }

  [super viewWillAppear:animated];

}

-(void) viewWillDisappear:(BOOL)animated {

  [[NSNotificationCenter defaultCenter] removeObserver:self]; 
   [super viewWillDisappear:animated];
  
}

-(void) viewDidDisappear:(BOOL)animated {

  [super viewDidDisappear:animated];
}

- (void)viewDidLoad
{
  UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addRSS:)] autorelease];
  self.navigationItem.leftBarButtonItem = addButton;
  self.title = NSLocalizedString(@"Sites", @"Sites");
  [super viewDidLoad];
  
  UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshRSS:)] autorelease];
  self.navigationItem.rightBarButtonItem = refreshButton;
  [self.navigationController setToolbarHidden:NO];
  // Uncomment the following line to preserve selection between presentations.
  // self.clearsSelectionOnViewWillAppear = NO;
  // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
  // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  // Return the number of sections.
  return 2 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  // Return the number of rows in the section.
  
  if ( [self.sitesArray count] == 0 ) {
    self.sitesArray = [self.base baseSites]; 
  }

  
  return section == 0?1:[self.sitesArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
  static NSString *CellIdentifier = @"Cell";
  
  UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    
    UILabel *allReadNum = [[[UILabel alloc] initWithFrame:CGRectMake(250, 10, 40, 25)]autorelease];
    
    //[allReadNum setText:[NSString stringWithFormat:@"%d", newsBase.listOfAllReadNews.count]];
    [allReadNum setAutoresizesSubviews:YES];
    [allReadNum setTextAlignment:UITextAlignmentCenter];
    allReadNum.clipsToBounds = YES;
    allReadNum.layer.cornerRadius = 10.0f;
    [allReadNum setFont:[UIFont boldSystemFontOfSize:10]];
    [allReadNum setTextColor:[UIColor whiteColor]];
    [allReadNum setBackgroundColor:[UIColor grayColor]];
    allReadNum.tag = 888;
    [cell addSubview:allReadNum];


  }
  
  UILabel *numberToRead = (UILabel *) [cell viewWithTag:888] ;
  
  if (indexPath.section == 0) {
    cell.textLabel.text = NSLocalizedString(@"All news", @"All news");
    numberToRead.text = [NSString stringWithFormat:@"%@", [self.base newArticles]];

    
  } else {
    cell.textLabel.text = [[ self.sitesArray objectAtIndex:indexPath.row]valueForKey:@"NAME"];
    
    
//    NSLog(@"%@", [[self.sitesArray objectAtIndex:indexPath.row]valueForKey:@"ID"]);
    
    numberToRead.text = [NSString stringWithFormat:@"%@", 
                         [self.base newArticlesForSiteID: [[self.sitesArray objectAtIndex:indexPath.row]valueForKey:@"ID"]]];
   
    
  }
  
  
  return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (indexPath.section == 1) {
//    [DataBase sharedDatabase].siteID = [[[[DataBase sharedDatabase] baseSites] objectAtIndex:indexPath.row]valueForKey:@"ID"];
//    NSLog(@"%@", [DataBase sharedDatabase].siteID);
    
    FeedsListViewController *feedsListViewController = [[FeedsListViewController alloc] init];
    feedsListViewController.siteID = [[[self.sitesArray objectAtIndex:indexPath.row] valueForKey:@"ID"]intValue];
    [self.navigationController pushViewController:feedsListViewController animated:YES];
    [feedsListViewController release];
  } else {
    MasterViewController *masterViewController = [[MasterViewController alloc] init];
    masterViewController.title = NSLocalizedString(@"All news", @"All news");
    [self.navigationController pushViewController:masterViewController animated:YES];
    [masterViewController release];
  }
    
}

- (void)addRSS:(id)sender {
  
  self.discoverFeedsViewController = [[[DiscoverFeedsViewController alloc] init] autorelease];
  self.discoverFeedsViewController.modalTransitionStyle = UIModalPresentationFormSheet;
  [self presentModalViewController:self.discoverFeedsViewController animated:YES]; 
  
}

- (void) pocessNotification:(NSNotification *) notification { 
  
  if ( [[notification name] isEqualToString:@"BaseUpdated"] )  {
    self.sitesArray = nil;
    [self.tableView reloadData]; 
  }
} 

- (void) refreshRSS: (id) sender {

  [[[[DataBase alloc]init]autorelease] updateAllFromInet];

}

@end
